package com.luo.demo.oidc.combo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain;

/**
 * OAuth2 第三方登录配置
 *
 * @author luohq
 * @date 2022-03-05 15:37
 */
@Configuration
public class Oauth2ThirdLoginConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE + 1) //在AuthServer后，在Form验证前
    SecurityFilterChain oauthLoginSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                //设置request matcher(仅针对需要进行OAuth Login验证的API进行拦截)
                .requestMatchers(requestMatchers -> requestMatchers
                        .mvcMatchers(
                                //OAuth2 Login认证端点（默认/oauth2/authorization/{clientId}）
                                OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/*",
                                //OAuth2 Login对调端点（默认/login/oauth2/code/{clientId}）
                                OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI
                                )
                )
                //授权设置
                .authorizeHttpRequests(authorize -> authorize
                        //集成自定义验证器
                        .anyRequest().authenticated()
                )
                //.oauth2Login(Customizer.withDefaults());
                .oauth2Login(oauth2Login -> oauth2Login
                        //本client内处理认证的端点（进入本client uri后自动根据client配置重定向到OP认证endpoint）
                        .authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint
                                .baseUri(OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI))
                        //code回调端点（第三方OAuth2平台通过此端点回调当前系统）
                        .redirectionEndpoint(redirectionEndpointConfig -> redirectionEndpointConfig
                                .baseUri(OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI)
                        )
                );
        return http.build();
    }
}
